import './assets/main.css'

import { createApp } from 'vue'
import store from '@/store/index'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import axios from 'axios'
import App from './App.vue'
import router from './router'

const app = createApp(App)
app.config.globalProperties.$api = axios
app.use(ElementPlus, { locale: zhCn })
app.use(router)
app.use(store)
app.mount('#app')

// 添加请求拦截器，在请求头中加token
axios.interceptors.request.use(
    config => {
        const token = store.state.Authorization;
        // console.log(token);
        if (token) {
            config.headers.Authorization = token;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);
axios.interceptors.response.use(
    response => {
        // console.log(response.headers); // 添加这行来查看所有响应头
        const newToken = response.data.token;
        if (newToken) {
            // 更新 Vuex 存储的 token
            store.dispatch('updateToken', `Bearer ${newToken}`);
            // 更新本地存储或其他 token 存储机制
            localStorage.setItem('Authorization', `Bearer ${newToken}`);
        }
        return response;
    }, error => {
        if (error.response && (error.response.status === 401 || error.response.status === 403)) {
            store.dispatch('logout');
            router.push('/login');
        }
        return Promise.reject(error);
    }
);